let nowClientWidth = document.documentElement.getBoundingClientRect().width;

// 打印标签属性
export const paddingTop = 8.0; //上边距
export const paddingLeft = 22.0; //左边距
export const padding6 = 6.0;
export const padding2 = 2.0;
export const logoWidth = 64.0; //logo宽
export const logoHeight = 24.0; //logo高
export const font36 = 36.0;
export const font32 = 32.0;
export const font16 = 26.0;
export const font10 = 22.0;
export const font8 = 16.0;
export const linePadding = 12.0; //行间隔
export const qrWidth80 = 42.0; //二维码大小
export const qrWidth = 104.0; //二维码大小
export const qrWidth130 = 128.0; //二维码大小
export const qrWidth150 = 150.0; //二维码大小
export const qrWidth200 = 208.0; //二维码大小
export const qrWidth250 = 224.0; //二维码大小
export const qrWidth280 = 232.0; //二维码大小
export const lineHeight10 = 54.0;
export const lineHeight8 = 34.0;
export const lineHeight6 = 24.0;
export const lineHeight4 = 18.0;
export const lineHeight18 = 45.0;
export const font18 = 19.0;

//换算方法
export function nowSize(val,initWidth=1920) {
  return val * (nowClientWidth / initWidth);
}

export function getDateRange(index) {
  let dateRange = '001'
  if(index == 0) {
    dateRange = '001'
  }else if(index == 1) {
    dateRange = '002'
  }else {
    dateRange = '003'
  }
  return dateRange
}
//数组分组
export function chunk(array, size) {
  let [start, end, result] = [null, null, []];
  for (let i = 0; i < Math.ceil(array.length / size); i++) {
    start = i * size;
    end = start + size;
    result.push(array.slice(start, end));
  }
  return result;
}

function addWan(integer, number, mutiple, decimalDigit) {
  var me = this;
  var digit = getDigit(integer);
  if (digit > 3) {
    var remainder = digit % 8;
    if (remainder >= 5) { // ‘十万’、‘百万’、‘千万’显示为‘万’
      remainder = 4;
    }
    return Math.round(number / Math.pow(10, remainder + mutiple - decimalDigit)) / Math.pow(10, decimalDigit) + '万';
  } else {
    return Math.round(number / Math.pow(10, mutiple - decimalDigit)) / Math.pow(10, decimalDigit);
  }
}
function getDigit(integer) {
  var digit = -1;
  while (integer >= 1) {
    digit++;
    integer = integer / 10;
  }
  return digit;
}
export function addChineseUnit(number, decimalDigit) {
  var me = this;
  decimalDigit = decimalDigit == null ? 2 : decimalDigit;
  var integer = Math.floor(number);
  var digit = getDigit(integer);
  // ['个', '十', '百', '千', '万', '十万', '百万', '千万'];
  var unit = [];
  if (digit > 3) {
    var multiple = Math.floor(digit / 8);
    if (multiple >= 1) {
      var tmp = Math.round(integer / Math.pow(10, 8 * multiple));
      unit.push(addWan(tmp, number, 8 * multiple, decimalDigit));
      for (var i = 0; i < multiple; i++) {
        unit.push('亿');
      }
      return unit.join('');
    } else {
      return addWan(integer, number, 0, decimalDigit);
    }
  } else {
    return number;
  }
}

export function download(src) {
  var form = document.createElement('form');
  form.action = src;
  document.getElementsByTagName('body')[0].appendChild(form);
  form.submit()
}

export function downloadAll(url) {
  let fileName = getFileName(url)
  var x = new XMLHttpRequest();
  x.open("GET", url, true);
  x.responseType = 'blob';
  x.onload=function(e) {
    var url = window.URL.createObjectURL(x.response)
    var a = document.createElement('a');
    a.href = url
    a.download = fileName;
    a.style.display = 'none'
    document.body.appendChild(a)
    a.click() // 点击下载
    document.body.removeChild(a) // 下载完成移除元素
  }
  x.send();
}
//获取文件名
export function getFileName(path) {
  var pos1 = path.lastIndexOf('/')
  var pos2 = path.lastIndexOf('\\')
  var pos = Math.max(pos1, pos2)
  if (pos < 0) {
    return path
  }
  else {
    let tempPath = path.substring(pos + 1);
    return tempPath.substring(0, tempPath.lastIndexOf("."));
  }
}

// 计算时间差
export function dateDiff(date1,date2) {
  let date1Str = date1.split("-");//将日期字符串分隔为数组,数组元素分别为年.月.日
  //根据年 . 月 . 日的值创建Date对象
  let date1Obj = new Date(date1Str[0],(date1Str[1]-1),date1Str[2]);
  let date2Str = date2.split("-");
  let date2Obj = new Date(date2Str[0],(date2Str[1]-1),date2Str[2]);
  let t1 = date1Obj.getTime();
  let t2 = date2Obj.getTime();
  let dateTime = 1000*60*60*24; //每一天的毫秒数
  let minusDays = Math.floor(((t2-t1)/dateTime));//计算出两个日期的天数差
  let days = Math.abs(minusDays);//取绝对值
  return days;
}
//是否显示tootip
export function visibilityChange(msg,width) {
  let app = document.querySelector('#app')
  // 这里需要用span，div默认是父盒子的宽度
  let span = document.createElement('span')
  span.style.fontSize ='14px'
  span.innerHTML = msg
  // 必须要添加到DOM树里面才有宽度，太狗了。所以对性能应该是有所影响的
  // 如果要优化肯定就在这里优化了，目前我还没有想到解决办法
  // 小弟愚钝，不知有没有大哥评论里面给个解决办法
  // 或者给一个全新的办法解决
  app.appendChild(span)
  let isShow = span.offsetWidth > width
  // 新增了当然要把他咔嚓掉嘛
  app.removeChild(span)
  return isShow
}

//字符串宽度
export function stringWidth(msg) {
  let app = document.querySelector('#app')
  // 这里需要用span，div默认是父盒子的宽度
  let span = document.createElement('span')
  span.style.fontSize ='14px'
  span.innerHTML = msg
  app.appendChild(span)
  let offsetWidth = span.offsetWidth
  // 新增了当然要把他咔嚓掉嘛
  app.removeChild(span)
  // console.log(offsetWidth)
  return offsetWidth
}

//是否显示tootip
export function visibilityChangeHome(msg,width) {
  let app = document.querySelector('#app')
  // 这里需要用span，div默认是父盒子的宽度
  let span = document.createElement('span')
  let n = document.body.clientWidth/1920
  span.style.fontSize = 14*n +'px'
  span.innerHTML = msg
  // 必须要添加到DOM树里面才有宽度，太狗了。所以对性能应该是有所影响的
  // 如果要优化肯定就在这里优化了，目前我还没有想到解决办法
  // 小弟愚钝，不知有没有大哥评论里面给个解决办法
  // 或者给一个全新的办法解决
  app.appendChild(span)
  let isShow = span.offsetWidth > width
  // 新增了当然要把他咔嚓掉嘛
  app.removeChild(span)
  return isShow
}

export function getScrollY(offsetHeight,extraHeight){
  return `calc(100vh - ${offsetHeight+extraHeight}px)`;
}
//更新数据到视图
export function updateData(list,key,item,value) {
  item[key] = value
  this.$delete(list,key)
  this.$set(list,key,item)
}

// 是否中文字符
export function containsChinese(str) {
  return /[\u4e00-\u9fff]/.test(str);
}

//当前日期
export function dateNow(seperator) {
  // 获取当前日期
  var date = new Date();

// 获取当前月份
  var nowMonth = date.getMonth() + 1;

// 获取当前是几号
  var strDate = date.getDate();

// 添加分隔符“-”
//   var seperator = "-";

// 对月份进行处理，1-9月在前面添加一个“0”
  if (nowMonth >= 1 && nowMonth <= 9) {
    nowMonth = "0" + nowMonth;
  }

// 对月份进行处理，1-9号在前面添加一个“0”
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }

// 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
 return date.getFullYear() + seperator + nowMonth + seperator + strDate;
}
//当前时间
export function timeNow() {
  let now = new Date(),
    y = now.getFullYear(),
    m = now.getMonth() + 1,
    d = now.getDate();
  return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d) + " " + now.toTimeString().substr(0, 8);
}

//当月天数
export function getMonthLength(year,month){
  return new Date(year, month, 0).getDate();
}

export function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

// 数字输入框限制只能输入大于等于零的整数
export function limitNumber(value){
  if (typeof value === 'string') {
    return !isNaN(Number(value)) ? value.replace(/\./g, '') : 0
  } else if (typeof value === 'number') {
    return !isNaN(value) ? String(value).replace(/\./g, '') : 0
  } else {
    return 0
  }
}

// 图片转为base64格式
export const imageToBase64 = (img) => {
  var canvas = document.createElement("canvas");
  canvas.width = img.width;
  canvas.height = img.height;
  var ctx = canvas.getContext("2d");
  ctx.drawImage(img, 0, 0, img.width, img.height);
  var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
  var dataURL = canvas.toDataURL("image/jpeg" + ext);
  return dataURL;
};

export const base64ToFile = (urlData, fileName) => {
  let arr = urlData.split(',');
  let mime = arr[0].match(/:(.*?);/)[1];
  let bytes = atob(arr[1]); // 解码base64
  let n = bytes.length
  let ia = new Uint8Array(n);
  while (n--) {
    ia[n] = bytes.charCodeAt(n);
  }
  return new File([ia], fileName, { type: mime });
}

//antd table合并单元格
export function renderContent(value){
  const obj = {
    children: value,
    attrs: {},
  };
  return obj;
}
export function rowSpan(data,key) {
  let arr = data
    .reduce((result, item) => {
      if (result.indexOf(item[key]) < 0) {
        result.push(item[key]);
      }
      return result;
    }, [])
    .reduce((result, keys) => {
      const children = data.filter((item) => item[key] === keys);
      result = result.concat(
        children.map((item, index) => ({
          ...item,
          [`${key}RowSpan`]: index === 0 ? children.length : 0,
        }))
      );
      return result;
    }, []);
  return arr
}

//百分比计算
export function GetPercent(num, total) {
  num = parseFloat(num);
  total = parseFloat(total);
  if (isNaN(num) || isNaN(total)) {
    return 0;
  }
  return total <= 0 ? "0%" : (Math.round(num / total * 10000) / 100.00);
}

//获取drawer宽度
export function drawerWith(){
  var clientWidth = document.body.clientWidth
  if(clientWidth > 1440) {
    return document.body.clientWidth - 220
  }else {
    return document.body.clientWidth - 200
  }
}

//数组去重
export function arrDistinctByProp(arr,prop){
  return arr.filter(function(item,index,self){
    return self.findIndex(el=>el[prop]==item[prop])===index
  })
}
//获取当前月份
export function getCurrentMonth(){
  return new Date().getFullYear()+'-'+((new Date().getMonth() + 1).toString()).padStart(2, '0')
}
//字符串是否包含html标签
export function containsHTML(str) {
  return /<[^>]*>/g.test(str);
}

//定时任务时间
//生产订单信息
export let orderTime = 10*60*1000
//成品交验合格率统计
export let productPassRateTime = 10*60*1000
//生产计划达成率统计
export let producePlanReachRateTime = 10*60*1000
//产品测试直通率统计
export let productTestFpyTime = 10*60*1000
//当月各工序日计划完成率排名
export let plansTime = 10*60*1000
//来料合格率统计
export let incomingRateTime = 10*60*1000
//设备监控
export let deviceTime = 10*60*1000

